package com.code.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.code.pojo.LoginLog;
import com.code.service.LoginLogService;
import com.code.util.GetIpAddress;
import com.code.util.WebUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Reference
    LoginLogService loginLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("登录成功啦!");
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        Browser browser = userAgent.getBrowser();
        LoginLog loginLog = new LoginLog();
//        String name = authentication.getName();
        loginLog.setLoginName(SecurityContextHolder.getContext().getAuthentication().getName());//当前登录用户名
        loginLog.setLoginTime(new Date());//登录时间
        loginLog.setBrowserName(browser.getName());//浏览器标识
        loginLog.setIp(GetIpAddress.getIpAddr(request));
        loginLog.setLocation(WebUtil.getCityByIP(loginLog.getIp()));
        ;loginLogService.addLoginLog(loginLog);
        request.getRequestDispatcher("/main.html").forward(request, response);
    }
}
